/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "math.h"
#include "oled.h"
#include "led.h"
#include <math.h>
#include <stdint.h>
#include "FreeRTOS_demo.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */
  Key_mark = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_DAC1_Init();
  MX_TIM2_Init();
  MX_TIM6_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  MX_ADC1_Init();
  MX_TIM1_Init();
  /* USER CODE BEGIN 2 */
  OLED_Init();
  OLED_Clear();
	HAL_TIM_Base_Start(&htim2);
	HAL_DAC_Start(&hdac1,DAC_CHANNEL_1);
  HAL_DAC_Start(&hdac1,DAC_CHANNEL_2);
  FreeRTOS_start();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    toggle_LED();
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV4;
  RCC_OscInitStruct.PLL.PLLN = 85;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/**
 * @brief 生成正弦波表（输出 _low 到 _high 之间的正弦波）。
 * @param _low  最低电压 (0 ~ 3.3V)
 * @param _high 最高电压 (0 ~ 3.3V)
 * @param buf   输出缓冲区，长度为 Num
 * @return 无
 */
void Generate_Sine(float _low, float _high, uint16_t buf[Num]) {
    // 限幅到 [0,3.3]
    if (_low < 0.0f) _low = 0.0f;
    if (_low > 3.3f) _low = 3.3f;
    if (_high < 0.0f) _high = 0.0f;
    if (_high > 3.3f) _high = 3.3f;
    // 确保低 ≤ 高
    if (_low > _high) {
        float tmp = _low; _low = _high; _high = tmp;
    }
    // 计算中值与振幅
    float mid = (_low + _high) * 0.5f;
    float amp = (_high - _low) * 0.5f;
    for (int i = 0; i < Num; ++i) {
        float angle = 2.0f * PI * (float)i / (float)Num;
        float value = mid + amp * sinf(angle);
        // 转换为12位DAC值
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
}
/**
 * @brief 生成等腰梯形波表（对称斜坡加可调平顶）。
 * @param _low  最低电压 (0 ~ 3.3V)
 * @param _high 最高电压 (0 ~ 3.3V)
 * @param duty  高电平（包括斜坡和平顶）总比例 (0 ~ 1)
 * @param flat  高电平中平顶部分的比例 (0 ~ 1)
 * @param buf   输出缓冲区，长度为 Num
 * @return 无
 */
void Generate_Trapezoid(float _low, float _high, float duty, float flat, uint16_t buf[Num]) {
    // 限幅并排序
    if (_low < 0.0f) _low = 0.0f;
    if (_low > 3.3f) _low = 3.3f;
    if (_high < 0.0f) _high = 0.0f;
    if (_high > 3.3f) _high = 3.3f;
    if (_low > _high) { float tmp = _low; _low = _high; _high = tmp; }
    // 限幅占空比和平顶比
    if (duty < 0.0f) duty = 0.0f;
    if (duty > 1.0f) duty = 1.0f;
    if (flat < 0.0f) flat = 0.0f;
    if (flat > 1.0f) flat = 1.0f;
    // 若 duty 或 flat 为 0，则退化为恒低
    if (duty <= 0.0f || flat <= 0.0f) {
        for (int i = 0; i < Num; ++i) buf[i] = (uint16_t)(_low * DAC_FULL_SCALE + 0.5f);
        return;
    }
    // 计算高电平总点数及各段点数
    int totalHigh = (int)(duty * Num + 0.5f);     // 包括斜坡和平顶
    if (totalHigh > Num) totalHigh = Num;
    int flatCount = (int)(flat * totalHigh + 0.5f);// 平顶点数
    if (flatCount > totalHigh) flatCount = totalHigh;
    int slopeTotal = totalHigh - flatCount;       // 两个斜坡点数之和
    int slopeDown = slopeTotal / 2;
    int slopeUp   = slopeTotal - slopeDown;
    int lowCount = Num - (slopeUp + flatCount + slopeDown); // 低电平段点数
    float range = _high - _low;
    int idx = 0;
    // 低电平起始段（底部平台）
    for (; idx < lowCount; ++idx) {
        buf[idx] = (uint16_t)(_low * DAC_FULL_SCALE + 0.5f);
    }
    // 上升斜坡
    for (int j = 0; j < slopeUp; ++j, ++idx) {
        float value = _low + range * ((float)(j + 1) / (float)slopeUp);
        buf[idx] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
    // 平顶部分
    for (int j = 0; j < flatCount; ++j, ++idx) {
        buf[idx] = (uint16_t)(_high * DAC_FULL_SCALE + 0.5f);
    }
    // 下降斜坡
    for (int j = 0; j < slopeDown; ++j, ++idx) {
        float value = _high - range * ((float)(j + 1) / (float)slopeDown);
        buf[idx] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
}

/**
 * @brief 生成占空比可调的非对称三角波表。
 * @param _low  最低电压 (0 ~ 3.3V)
 * @param _high 最高电压 (0 ~ 3.3V)
 * @param duty  上升时间占周期的比例 (0 ~ 1)
 * @param buf   输出缓冲区，长度为 Num
 * @return 无
 */
void Generate_AsymTriangle(float _low, float _high, float duty, uint16_t buf[Num]) {
    // 限幅并排序
    if (_low < 0.0f) _low = 0.0f;
    if (_low > 3.3f) _low = 3.3f;
    if (_high < 0.0f) _high = 0.0f;
    if (_high > 3.3f) _high = 3.3f;
    if (_low > _high) {
        float tmp = _low; _low = _high; _high = tmp;
    }
    // 限幅占空比
    if (duty < 0.0f) duty = 0.0f;
    if (duty > 1.0f) duty = 1.0f;
    // 若 duty 为 0 或 1，退化为恒低或恒高
    if (duty <= 0.0f) {
        for (int i = 0; i < Num; ++i) buf[i] = (uint16_t)(_low * DAC_FULL_SCALE + 0.5f);
        return;
    }
    if (duty >= 1.0f) {
        for (int i = 0; i < Num; ++i) buf[i] = (uint16_t)(_high * DAC_FULL_SCALE + 0.5f);
        return;
    }
    // 计算上升段结束的索引
    int peakIndex = (int)(duty * (Num - 1) + 0.5f);
    float range = _high - _low;
    // 上升段：0..peakIndex 线性从低到高
    for (int i = 0; i <= peakIndex; ++i) {
        float value = _low + range * ((float)i / (float)peakIndex);
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
    // 下降段：peakIndex+1..Num-1 线性从高到低
    for (int i = peakIndex + 1; i < Num; ++i) {
        float value = _high - range * ((float)(i - peakIndex) / (float)(Num - 1 - peakIndex));
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
}
/**
 * @brief 生成等腰三角波表（线性上升后线性下降）。
 * @param _low  最低电压 (0 ~ 3.3V)
 * @param _high 最高电压 (0 ~ 3.3V)
 * @param buf   输出缓冲区，长度为 Num
 * @return 无
 */
void Generate_Triangle(float _low, float _high, uint16_t buf[Num]) {
    // 限幅并排序
    if (_low < 0.0f) _low = 0.0f;
    if (_low > 3.3f) _low = 3.3f;
    if (_high < 0.0f) _high = 0.0f;
    if (_high > 3.3f) _high = 3.3f;
    if (_low > _high) {
        float tmp = _low; _low = _high; _high = tmp;
    }
    float range = _high - _low;
    int half = Num / 2;
    // 上升段：0..half-1 点由 low 增到 high
    for (int i = 0; i < half; ++i) {
        float value = _low + range * ((float)i / (float)(half - 1));
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
    // 下降段：half..Num-1 点由 high 降到 low
    for (int i = half; i < Num; ++i) {
        float value = _high - range * ((float)(i - half) / (float)(half - 1));
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
}

/**
 * @brief 生成占空比可调的矩形波表。
 * @param _low  低电平电压 (0 ~ 3.3V)
 * @param _high 高电平电压 (0 ~ 3.3V)
 * @param duty  占空比 (0 ~ 1，高电平所占比例)
 * @param buf   输出缓冲区，长度为 Num
 * @return 无
 */
void Generate_Rectangular(float _low, float _high, float duty, uint16_t buf[Num]) {
    // 限幅并排序
    if (_low < 0.0f) _low = 0.0f;
    if (_low > 3.3f) _low = 3.3f;
    if (_high < 0.0f) _high = 0.0f;
    if (_high > 3.3f) _high = 3.3f;
    if (_low > _high) {
        float tmp = _low; _low = _high; _high = tmp;
    }
    // 限幅占空比在 [0,1]
    if (duty < 0.0f) duty = 0.0f;
    if (duty > 1.0f) duty = 1.0f;
    // 计算高电平持续的采样点数
    int highCount = (int)(duty * Num + 0.5f);
    if (highCount < 0) highCount = 0;
    if (highCount > Num) highCount = Num;
    // 填充波形：前 highCount 点为高电平，之后为低电平
    for (int i = 0; i < Num; ++i) {
        float value = (i < highCount) ? _high : _low;
        buf[i] = (uint16_t)(value * DAC_FULL_SCALE + 0.5f);
    }
}

/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM17 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM17)
  {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
